﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using BBICMS.Model;
using BBICMS.Repository;
using System.Data.Entity.Infrastructure;
using System.Data.Entity;
using BBICMS.WebUI.Filters;

namespace BBICMS.WebUI.Controllers
{
     [SIGAuth]
    public class ProductsAPIController : ApiController
    {
        public ApplicationUnit _unit = new ApplicationUnit();

        [HttpGet]
        [AllowAnonymous]
        public IEnumerable<Product> Get()
        {
            return this._unit.Products.GetAll();
        }



        [HttpGet]
        [ActionName("Edit")]
        [AllowAnonymous]
        [System.Web.Http.Authorize(Roles = "Administrators, Users")]
        public Product Get(int id)
        {
            Product product = this._unit.Products.GetById(id);
            if (product == null)
            {
                throw new HttpResponseException(
                    Request.CreateResponse(HttpStatusCode.NotFound));
            }

            return product;
        }
        [HttpPut]
        [AllowAnonymous]
       // [System.Web.Http.Authorize(Roles = "Administrators, Users")]
        public HttpResponseMessage Put(int id, Product product)
        {
            if (!ModelState.IsValid)
            {
                return Request.
                    CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            if (id != product.Id)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            Product existingProduct = this._unit.Products.GetById(id);
            //_unit.Products.Detach(existingProduct);

            // Keep original CreatedOn value
          //  existingProduct.CategoryIds = product.CategoryIds;   
          //  existingProduct.ProductName = product.ProductName;
            existingProduct.ProductNo = product.ProductNo;
            //existingProduct.Parameters = product.Parameters;
            //existingProduct.Description = product.Description;
          //  existingProduct.Summary = product.Summary;
            //existingProduct.ImageUrl = product.ImageUrl;
            //existingProduct.Keywords = product.Keywords;
            //existingProduct.ViewImage = product.ViewImage;
            existingProduct.Thumbnail = product.Thumbnail;
            existingProduct.Active = product.Active;

            //int[] arrCategories = product.CategoryIds.Split(',').Select(n => Convert.ToInt32(n)).ToArray();
            //var lCategories = (from c in _unit.Categories.GetAll()
            //                   where arrCategories.Contains(c.Id)
            //                   select c).ToList();

           // existingProduct.Categories.Clear();
            //foreach (Category c in lCategories)
            //{
            //    existingProduct.Categories.Add(c);
            //}


            this._unit.Products.Update(existingProduct);

            try
            {
                this._unit.SaveChanges();

                // Return an explicit value to avoid the fail callback
                // being incorrectly invoked.
                return Request.
                    CreateResponse(HttpStatusCode.OK,
                    "{success:'true', verb:'PUT'}");
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.
                    CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }
            catch (Exception ex)
            {
                return Request.
                    CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
        }

        [HttpPost]
        [System.Web.Http.Authorize(Roles = "Administrators, Users")]
        public HttpResponseMessage Product(Product product)
        {
            try
            {
                if (ModelState.IsValid)
                {
                   // int[] arrCategories = product.CategoryIds.Split(',').Select(n => Convert.ToInt32(n)).ToArray();
                    //var allCategories = _unit.Categories.GetAll().ToList();
                    //var lCategories = (from c in allCategories
                    //                      where arrCategories.Contains(c.Id)
                    //                      select c).ToList();

                    //product.Categories = new List<Category>();
                    //foreach(Category c in lCategories){
                    //    product.Categories.Add(c);
                    //}                    

                    this._unit.Products.Add(product);
                    this._unit.SaveChanges();

                    HttpResponseMessage result =
                        Request.CreateResponse(HttpStatusCode.Created, product);

                    result.Headers.Location =
                        new Uri(Url.Link("DefaultApi", new { id = product.Id }));

                    return result;
                }
                else
                {
                    return Request.
                        CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
                }
            }
            catch (Exception ex)
            {
                return Request.
                    CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
        }

        [HttpDelete]
        [System.Web.Http.Authorize(Roles = "Administrators, Users")]
        public HttpResponseMessage Delete(int id)
        {
            Product product = this._unit.Products.GetById(id);

            if (product == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }
          
            this._unit.Products.Delete(product);

            try
            {
                this._unit.SaveChanges();
                return Request.CreateResponse(HttpStatusCode.OK, product);
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.
                    CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }
        }

        protected override void Dispose(bool disposing)
        {
            this._unit.Dispose();
            base.Dispose(disposing);
        }
    }
}
